import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import '../../../../utils/storage/storage.dart';
import '../../../../models/message_model.dart';
import '../../../../service/HttpsClient.dart';
import '../../../../modules/user/controllers/user_controller.dart';

class CodeLoginStepTwoController extends GetxController {
  //TODO: Implement CodeLoginStepTwoController
  TextEditingController codeController = TextEditingController();
  UserController userController = Get.find<UserController>(); // 引入用户模块的controller
  HttpsClient httpsClient = HttpsClient();
  RxInt seconds = 10.obs; // 倒计时秒数

  // 开始倒计时
  void startDownCount() {
    // 开启定时器
    if (seconds.value > 0) {
      Timer.periodic(const Duration(milliseconds: 1000), (Timer timer) {
        if (seconds.value > 0) {
          seconds.value--;
        } else {
          timer.cancel();
        }
      });
    }
    update(); // 更新UI
  }

  // 重新发送验证码
  Future<bool> sendCode(String tel) async {
    var response = await httpsClient.post('api/sendCode', data: {'tel': tel});
    print(response);
    if (response != null) {
      if (response['success'] == true) {
        Clipboard.setData(ClipboardData(text: response['code']));
        seconds.value = 10; // 重置倒计时
        startDownCount(); // 开始倒计时
        return true;
      }

      return false;
    }
    return false;
  }

  // 验证码登录
  Future<MessageModel> goCodeLogin() async {
    String username = Get.arguments["tel"];
    String code = codeController.text;
    if (code.isEmpty) {
      return MessageModel(success: false, message: "请输入验证码");
    }
    if (code.length <6) {
      return MessageModel(success: false, message: "请输入完整的验证码");
    }

    var response = await httpsClient.post(
      "api/validateLoginCode",
      data: {"code": code, "tel": username},
    );
    if (response != null) {
      if (response["success"]) {
        Storage.setData("userinfo", response["userinfo"]); // 登录成功存入缓存
        return MessageModel(success: true, message: "登录成功");
      } else {
        return MessageModel(success: false, message: response["message"]);
      }
    } else {
      return MessageModel(success: false, message: "网络错误");
    }
  }

  @override
  void onInit() {
    super.onInit();
    startDownCount(); // 开始倒计时
  }

  @override
  void onClose() {
    super.onClose();
    userController.getUserinfo(); // 重新获取用户信息
  }
}
